package com.quectel.cms.controller.application;


import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.application.dto.ApplicationAccessTemplateDto;
import com.quectel.core.module.application.service.ApplicationAccessTemplateService;
import com.quectel.core.module.device.dto.DeviceTypeDto;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author rananxin
 * @date 2021-11-09 09:48:18
 */
@RestController
@RequestMapping("applicationAccessTemplate")
@Tag(name = "ApplicationAccessTemplateController", description = "应用配置模版表相关api")
public class ApplicationAccessTemplateController extends BaseController {

    @DubboReference
    private ApplicationAccessTemplateService applicationAccessTemplateService;
    @DubboReference
    private DeviceTypeService deviceTypeService;

    @GetMapping("queryAll")
    @Operation(summary = "应用配置模版的查询列表")
    public Response<List<ApplicationAccessTemplateDto>> info(@RequestParam Map<String, Object> params) {
        List<ApplicationAccessTemplateDto> applicationAccessTemplateDtos = applicationAccessTemplateService.queryList(params);
        return Response.<List<ApplicationAccessTemplateDto>>ok().wrap(applicationAccessTemplateDtos);
    }


    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "applicationAccessTemplate:list")
    @Operation(summary = "应用配置模版的分页查询列表")
    public Response<Page<ApplicationAccessTemplateDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = applicationAccessTemplateService.queryTotal(request.getParams());

        List<ApplicationAccessTemplateDto> list = null;
        if (total > 0) {
            list = applicationAccessTemplateService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ApplicationAccessTemplateDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ApplicationAccessTemplateDto>>ok().wrap(page);
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "applicationAccessTemplate:info")
    @Operation(summary = "查询单条应用配置模版记录")
    public Response<ApplicationAccessTemplateDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (applicationAccessTemplateService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ApplicationAccessTemplateDto applicationAccessTemplateDto = applicationAccessTemplateService.selectById(id);

        return Response.<ApplicationAccessTemplateDto>ok().wrap(applicationAccessTemplateDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "applicationAccessTemplate:edit")
    @Operation(summary = "保存单条应用配置模版记录")
    public Response<Object> save(@RequestBody @Validated ApplicationAccessTemplateDto applicationAccessTemplateDto) {

        DeviceTypeDto deviceTypeDto = deviceTypeService.selectById(applicationAccessTemplateDto.getDeviceTypeId());
        if (deviceTypeDto == null) {
            return Response.error("null deviceType");
        }

        ApplicationAccessTemplateDto.protocolTypeEnum protocolTypeEnum = ApplicationAccessTemplateDto.protocolTypeEnum
                .getByProtocolType(applicationAccessTemplateDto.getProtocolType());

        ApplicationAccessTemplateDto oldDto = applicationAccessTemplateService
                .selectByTypeAndConf(deviceTypeDto.getId(), applicationAccessTemplateDto.getAccessConfId());

        if (oldDto != null) {
            return Response.error("template already exists");
        }

        if (ApplicationAccessTemplateDto.protocolTypeEnum.TCP.equals(protocolTypeEnum)) {
            List<ApplicationAccessTemplateDto> portConfList = applicationAccessTemplateService.queryList(new HashMap<String, Object>() {{
                put("port", applicationAccessTemplateDto.getPort());
            }});
            if (portConfList != null && portConfList.size() > 0) {
                return Response.error("port is occupied");
            }
        }

        //填充基础数据
        fillSaveCommonData(applicationAccessTemplateDto);

        applicationAccessTemplateService.save(applicationAccessTemplateDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "applicationAccessTemplate:edit")
    @Operation(summary = "修改单条应用配置模版记录")
    public Response<Object> update(@RequestBody @Validated ApplicationAccessTemplateDto applicationAccessTemplateDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(applicationAccessTemplateDto.getId()));
        if (applicationAccessTemplateService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(applicationAccessTemplateDto);

        applicationAccessTemplateService.updateById(applicationAccessTemplateDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "applicationAccessTemplate:delete")
    @Operation(summary = "批量删除存在的应用配置模版记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (applicationAccessTemplateService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        applicationAccessTemplateService.deleteBatch(ids);

        return Response.ok();
    }
}
